package com.atguigu.flink.timer;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/11/25
 *
 *  计算每种传感器的水位和
 *          ReducingState: 聚合的输入和输出必须是一致的！两两聚合！
 */
public class Demo6_ReducingState
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           .keyBy(WaterSensor::getId)
           .process(new KeyedProcessFunction<String, WaterSensor, String>()
           {

               private ReducingState<WaterSensor> state;

               @Override
               public void open(Configuration parameters) throws Exception {
                   state = getRuntimeContext().getReducingState(new ReducingStateDescriptor<WaterSensor>("sum", new ReduceFunction<WaterSensor>()
                   {
                       @Override
                       public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                           value2.setVc(value1.getVc() + value2.getVc());
                           return value2;
                       }
                   }, WaterSensor.class));
               }

               @Override
               public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                   //来一条数据，放入状态
                   state.add(value);

                   //获取聚合后的结果
                   WaterSensor waterSensor = state.get();

                   out.collect(ctx.getCurrentKey() + ":" + waterSensor.getVc());

               }
           }).print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
